<?php
namespace app\index\controller;
require_once __DIR__."/../../../extend/ItemsApi.php";
use think\Request;
use think\facade\Session;
use think\Response;
use think\exception\HttpResponseException;
use app\index\model\ChannelInfo as ChannelInfo;
use think\facade\Config;;

class Shop
{
    protected $ItemApi = null;

     /**
     * 默认响应输出类型,支持json/xml
     * @var string 
     */
    protected $responseType = 'json';

    /**
     * @var Request Request 实例
     */
    protected $request;

    public function __construct(Request $request = null){
        $this->request = is_null($request) ? Request::instance() : $request;
        $options = Config::get('taobao_api_params');
        $this->ItemsApi = new \ItemsApi($options);
    }

    public function index()
    {
        $page_size = $this->request->param('page_size')??20;
        $page_no = $this->request->param('page_no')??1;
        $is_overseas = $this->request->param('is_overseas')??false;
        $is_tmall = $this->request->param('is_tmall')??false;
        $q = $this->request->param('q')??"女装";
        $has_coupon = $this->request->param('has_coupon')??false;
        $sort_type = $this->request->param('sort_type')??0;

        $resp = $this->ItemsApi->search($q, $is_overseas, $is_tmall, $has_coupon, $sort_type, $page_no, $page_size);
        $resp = $this->addRate($resp);
        $this->result("success", $resp);
        return ;
    }

    public function detail(){
        $num_iid = $this->request->param('num_iid')??'';

        if(!$num_iid){
            $this->result("缺少参数num_iid", [], '-1');
        }
        $resp = $this->ItemsApi->detail($num_iid);
        $resp = $this->change_detail_info($resp);
        $this->result("success", $resp);
        return ;
    }

    protected function change_detail_info($data){
        if(!$data){
            return $data;
        }
        $data = $this->object_array($data);
        if(array_key_exists("results", $data) && $data['results']['n_tbk_item']){
            if($data['results']['n_tbk_item']['small_images'] && $data['results']['n_tbk_item']['small_images']['string']){
                if(!is_array($data['results']['n_tbk_item']['small_images']['string'])){
                    $tmp_arr = [];
                    $tmp_arr[] = $data['results']['n_tbk_item']['small_images']['string'];
                    $data['results']['n_tbk_item']['small_images']['string'] = $tmp_arr;
                }
            }
        }
        return $data;
    }

    protected function addRate($data){
        if(!$data){
            return $data;
        }
        $data = $this->object_array($data);
        if(array_key_exists("result_list", $data) && $data['result_list']['map_data']){
            $list = $data['result_list']['map_data'];
            if(is_array($list) && array_key_exists("coupon_info", $list)){
                $tmp_arr = [];
                $tmp_arr[] = $list;
                $list = $tmp_arr;
            }
            foreach($list as $k => $v){
                if(!is_array($v) || !array_key_exists("coupon_info", $v)){
                    continue;
                }
                $couponMoney = 0;
                $v['zk_final_price'] = round($v['zk_final_price'], 2);
                if(is_string($v['coupon_info']) && strstr($v['coupon_info'], '减')){
                   $v['coupon_info'] = str_replace(".00", "", $v['coupon_info']);
                   $couponMoney = explode("减", $v['coupon_info']);
                   $couponMoney = str_replace("元", "", $couponMoney[1]);
                }else{
                    $v['coupon_info'] = '';
                    $v['coupon_amount'] = 0;
                }
                $rate_list = ChannelInfo::getUserRates(1, $v['zk_final_price'], $v['commission_rate']/10000, $couponMoney);
                $v['user_income'] = $rate_list['user_income'];
                $v['user_income_rate'] = $rate_list['user_income_rate'];
                $v['coupon_income'] = $rate_list['coupon_income'];

                $list[$k] = $v;
            }
            $data['result_list']['map_data'] = $list;
        }
        return $data;
    }

    function object_array($array){
      if(is_object($array)){
        $array = (array)$array;
      }
      if(is_array($array)){
        foreach($array as $key=>$value){
          $array[$key] = $this->object_array($value);
        }
      }
      return $array;
  }

    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => $this->request->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode']))
        {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        }
        else
        {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }
}
